<?php 

class File {

    //内容
    protected $_content;
    //路径
    protected $_filePath;

    public function __construct($filePath, $content = '') {
        $this->_filePath    = $filePath;
        $this->_content     = $content; 
    }

    public function save() {
        if(false === $this->verifyDir()) {
            if(false === $this->createNewDir()) {
                return false;
            }
        }

        return $this->saveFile();
    }

    public function open() {
        if(false === $this->verifyFile()) {
            return false;
        }

        return $this->openFile();
    }

    protected function verifyFile() {
        if(!file_exists($this->_filePath)) {
            Logger::log('文件不存在！' . $this->_filePath);
            return false;
        }
        if(!is_readable($this->_filePath)) {
            Logger::log('文件不可读！' . $this->_filePath);
            return false;
        }

        return true;
    }

    protected function verifyDir() {
        $dirPath    = './' . dirname($this->_filePath);
        if(!file_exists($dirPath)) {
            Logger::log('文件夹不存在！' . $dirPath);
            return false;
        }

        return true;
    }

    protected function createNewDir() {
        $dirs   = explode('/', dirname($this->_filePath));
        $dirPath    = './';
        foreach($dirs as $dirName) {
            if(file_exists($dirPath . $dirName)) {
                continue;
            }
            $dirPath    .= '/' . $dirName;
            if(!mkdir($dirPath)) {
                Logger::log('文件夹创建不成功！' . __FILE__ . '/' . $dirPath);
                return false;
            } else {
                Logger::log('文件夹创建成功！' . $dirPath);
            }
        }

        return true;
    }

    public function saveFile() {
        if(file_put_contents($this->_filePath, $this->_content)) {
            return true;
        }

        return false;
    }

    public function appendFile() {
        if($fileHandle = fopen($this->_filePath, 'a+')) {
            fwrite($fileHandle, $this->_content);
            fclose($fileHandle);
        }
    }

    public function openFile() {
        return file_get_contents($this->_filePath);
    }

    public function getFilePath() {
        return $this->_filePath;    
    }

    public function getContent() {
        return $this->_content;
    }

}

?>
